//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ty.pdm.system.workFlow.listener.common;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.basedrule.dto.TyplmBaseRuleBoundedObjDTO;
import com.hustcad.plm.pdm.basedrule.service.TyplmBasedRuleService;
import com.hustcad.plm.pdm.baseline.module.dto.BaseLineDTO;
import com.hustcad.plm.pdm.baseline.module.dto.TyplmBaseLineMemberAddDTO;
import com.hustcad.plm.pdm.baseline.module.vo.TyplmBaseLineMemberCheckResultVO;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineMemberService;
import com.hustcad.plm.pdm.baseline.service.TyplmBaseLineService;
import com.hustcad.plm.pdm.container.model.entity.Container;
import com.hustcad.plm.pdm.container.service.ContainerService;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowChgFormView;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.type.model.vo.TypeTree;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.*;

@CustomListener(
        category = "永续基线监听",
        description = "永续基线接口"
)
public class BaseLineListener implements ExecutionListener {
    private static final Logger log = LoggerFactory.getLogger(BaseLineListener.class);
    private static final long serialVersionUID = -9059663559349037414L;


    public BaseLineListener() {

    }

    public void notify(DelegateExecution execution) {
        try {
            log.info("开始执行监听 ==> 物料申请 BaseLineListener");
            String workFlowContainerIdStr = execution.getProcessInstanceBusinessKey();
            BigInteger workFlowContainerId = new BigInteger(workFlowContainerIdStr);
            TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(
                    TyplmWorkFlowContainerService.class);
            if (typlmWorkFlowContainerService != null) {
                WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                        workFlowContainerId);
                if (workFlowContainerView instanceof WorkFlowObjectPackage) {
                    WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
                    if (workFlowObjectPackage.getFlowObjectList() != null && workFlowObjectPackage.getFlowObjectList()
                            .size() != 0) {
                        for (int i = 0; i < workFlowObjectPackage.getFlowObjectList().size(); i++) {
                            FlowObject flowObject = workFlowObjectPackage.getFlowObjectList().get(i);

                            String oType = flowObject.getRefObjectOtype();
                            if ("ty.inteplm.part.CTyPart".equals(oType)) {
                                int result = (int) extendedTask(flowObject);
                                if (result != 1) {
                                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                                            "extendedTask返回错误");
                                }
                            }
                        }
                    } else {
                        throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("getFlowObjectList为空");
                    }
                } else if (workFlowContainerView instanceof FlowChgFormView) {
                    FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
                    if (flowChgFormView.getChgFormVO() != null && flowChgFormView.getChgFormVO()
                            .getEcAffectVOS() != null) {
                        //排除重复的编码
                        Map<String, Object> cmd = new HashMap<>();
                        for (int i = 0; i < flowChgFormView.getChgFormVO().getEcAffectVOS().size(); i++) {
                            ECObjData ecObjData = flowChgFormView.getChgFormVO().getEcAffectVOS().get(i);
                            if (cmd.containsKey(ecObjData.getNumber())) {
                                continue;
                            } else {
                                cmd.put(ecObjData.getNumber(), "1");
                            }
                            extendedTaskEco(ecObjData);
                        }
                    }
                } else {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("WorkFlowObjectPackage错误");
                }
            } else {
                throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("TyplmWorkFlowContainerService无法加载");
            }

            log.info("正常执行监听结束 <== 物料申请 BaseLineListener");
        } catch (Exception var5) {
            log.error("监听BaseLineListener异常：" + var5);
            var5.printStackTrace();
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(var5.getMessage());
        }
    }

    /**
     * 评审流程打基线
     *
     * @param flowObject
     * @return
     */
    public int extendedTask(FlowObject flowObject) {

        try{
            TyplmBaseLineMemberService typlmBaseLineMemberService = SpringUtil.getBean(TyplmBaseLineMemberService.class);
            TyplmBaseLineService typlmBaseLineService = SpringUtil.getBean(TyplmBaseLineService.class);
            TyplmPartService typlmPartService = (TyplmPartService) SpringUtil.getBean(
                    TyplmPartService.class);

            if ("ty.inteplm.part.CTyPart".equals(flowObject.getRefObjectOtype()) == false) {
                return 1;
            }

            BigInteger oid = flowObject.getRefObjectOid();
            String oType = flowObject.getRefObjectOtype();
            PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);


            List<BaseLineDTO> baseLineDTOList = new ArrayList<>();
            BaseLineDTO baseLineDTO = new BaseLineDTO();


            baseLineDTO.setContainerId(partDetailsVO.getContaineroid());
            baseLineDTO.setContainerType(partDetailsVO.getContainerotype());
            baseLineDTO.setContainerName(partDetailsVO.getContainerName());

            baseLineDTO.setFolderId(String.valueOf(partDetailsVO.getFolderId()));
            baseLineDTO.setFolderPath(partDetailsVO.getFolderPath());

            baseLineDTO.setIbaAttributeMap(new HashMap<>());
            baseLineDTO.setIsProtected("Y");
            baseLineDTO.setLock("N");

            ContainerService containerService = SpringUtil.getBean(ContainerService.class);

            Container container = containerService.select(new BigInteger(partDetailsVO.getContaineroid()),
                                                          partDetailsVO.getContainerotype());

            BigInteger typeOid = null;
            TyplmTypeService typlmTypeService = SpringUtil.getBean(TyplmTypeService.class);

            List<TypeTree> typeTrees = typlmTypeService.getFilterPlanTypeListByoType("ty.inteplm.baseline.CTyBaseLine");

            if (typeTrees != null && typeTrees.size() > 0) {
                typeOid = typeTrees.get(0).getOid();
            }

            TyplmBasedRuleService typlmBasedRuleService = SpringUtil.getBean(TyplmBasedRuleService.class);


            TyplmBaseRuleBoundedObjDTO typeBasedRuleEditDTO = typlmBasedRuleService.getBaseRuleBoundedObjInfo(typeOid,
                                                                                                              new BigInteger(
                                                                                                                      container.getContainerOid()),
                                                                                                              container.getContainerOtype());
            baseLineDTO.setClassId(String.valueOf(typeBasedRuleEditDTO.getClassificationOid()));


            baseLineDTO.setName(partDetailsVO.getIdentifierDisplayName());

            baseLineDTO.setTopObjectOType(partDetailsVO.getContainerotype());
            baseLineDTO.setTopObjectOid(partDetailsVO.getContaineroid());
            if (typeTrees != null && typeTrees.size() > 0) {
                baseLineDTO.setTypeOid(typeTrees.get(0).getOid());
                baseLineDTO.setTypeOtype(typeTrees.get(0).getOtype());
            }


            baseLineDTOList.add(baseLineDTO);
            List<BigInteger> oidList = typlmBaseLineService.batchCreateBaseLine(baseLineDTOList);
            if (oidList != null && oidList.size() > 0) {
                TyplmBaseLineMemberAddDTO typlmBaseLineMemberAddDTO = new TyplmBaseLineMemberAddDTO();
                IdentifierEntity baseLineEntity = new IdentifierEntity();
                baseLineEntity.setOid(new BigInteger(String.valueOf(oidList.get(0))));
                baseLineEntity.setOtype("ty.inteplm.baseline.CTyBaseLine");

                List<IdentifierEntity> refObjList = new ArrayList<>();
                IdentifierEntity refEntity = new IdentifierEntity();
                refEntity.setOid(new BigInteger(String.valueOf(partDetailsVO.getOid())));
                refEntity.setOtype(partDetailsVO.getOtype());
                refObjList.add(refEntity);


                TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
                if (typlmPartBomService != null) {
                    com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                    expandBomTreeByFilterDTO.setFatherOid(String.valueOf(flowObject.getRefObjectOid()));
                    expandBomTreeByFilterDTO.setExpandLevel("N");
                    expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                    expandBomTreeByFilterDTO.setIsQueryIBA(true);
                    expandBomTreeByFilterDTO.setIsNestedTree(false);

                    ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                    childPartsFiltersDTO.setView(flowObject.getView());
                    childPartsFiltersDTO.setExpandCondition("latest");
                    List<ChildPartsFiltersDTO> list = new ArrayList<>();
                    list.add(childPartsFiltersDTO);
                    expandBomTreeByFilterDTO.setConditions(list);
                    PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                                Boolean.TRUE);

                    for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                        PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                        if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                            refEntity = new IdentifierEntity();
                            refEntity.setOid(new BigInteger(String.valueOf(partBomTree.getPartoid())));
                            refEntity.setOtype(partBomTree.getPartotype());
                            refObjList.add(refEntity);
                        }
                    }
                }


                typlmBaseLineMemberAddDTO.setBaseLineInfo(baseLineEntity);
                typlmBaseLineMemberAddDTO.setRefObjList(refObjList);

                TyplmBaseLineMemberCheckResultVO typlmBaseLineMemberCheckResultVO = typlmBaseLineMemberService.checkObjectAddBaseLine(
                        typlmBaseLineMemberAddDTO);

                if(typlmBaseLineMemberCheckResultVO.getErrorList()!=null && typlmBaseLineMemberCheckResultVO.getErrorList().size()>0){
                    StringBuilder error=new StringBuilder();
                    for(int a=0;a<typlmBaseLineMemberCheckResultVO.getErrorList().size();a++){
                        if(error.length()>0) error.append(",");
                        error.append(typlmBaseLineMemberCheckResultVO.getErrorList().get(a).getDisplayName()+typlmBaseLineMemberCheckResultVO.getErrorList().get(a).getMessage());
                    }
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(error);

                }
                boolean flag = typlmBaseLineMemberService.addBaseLineMember(typlmBaseLineMemberCheckResultVO);
                if (flag == true) {
                    return 1;
                }

            }
        }
        catch (Exception e){
            e.printStackTrace();
            throw e;
        }


        return -1;
    }

    /**
     * 变更流程打基线
     *
     * @param ecObjData
     * @return
     */
    public int extendedTaskEco(ECObjData ecObjData) {

        TyplmBaseLineMemberService typlmBaseLineMemberService = SpringUtil.getBean(TyplmBaseLineMemberService.class);
        TyplmBaseLineService typlmBaseLineService = SpringUtil.getBean(TyplmBaseLineService.class);
        TyplmPartService typlmPartService = (TyplmPartService) SpringUtil.getBean(
                TyplmPartService.class);
        if ("ty.inteplm.part.CTyPart".equals(ecObjData.getOtype()) == false) {
            return 1;
        }

        BigInteger oid = ecObjData.getRefObjectOid();
        String oType = ecObjData.getRefObjectOtype();
        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);


        List<BaseLineDTO> baseLineDTOList = new ArrayList<>();
        BaseLineDTO baseLineDTO = new BaseLineDTO();


        baseLineDTO.setContainerId(partDetailsVO.getContaineroid());
        baseLineDTO.setContainerType(partDetailsVO.getContainerotype());
        baseLineDTO.setContainerName(partDetailsVO.getContainerName());

        baseLineDTO.setFolderId(String.valueOf(partDetailsVO.getFolderId()));
        baseLineDTO.setFolderPath(partDetailsVO.getFolderPath());

        baseLineDTO.setIbaAttributeMap(new HashMap<>());
        baseLineDTO.setIsProtected("Y");
        baseLineDTO.setLock("N");

        ContainerService containerService = SpringUtil.getBean(ContainerService.class);

        Container container = containerService.select(new BigInteger(partDetailsVO.getContaineroid()),
                                                      partDetailsVO.getContainerotype());

        BigInteger typeOid = null;
        TyplmTypeService typlmTypeService = SpringUtil.getBean(TyplmTypeService.class);

        List<TypeTree> typeTrees = typlmTypeService.getFilterPlanTypeListByoType("ty.inteplm.baseline.CTyBaseLine");

        if (typeTrees != null && typeTrees.size() > 0) {
            typeOid = typeTrees.get(0).getOid();
        }

        TyplmBasedRuleService typlmBasedRuleService = SpringUtil.getBean(TyplmBasedRuleService.class);


        TyplmBaseRuleBoundedObjDTO typeBasedRuleEditDTO = typlmBasedRuleService.getBaseRuleBoundedObjInfo(typeOid,
                                                                                                          new BigInteger(
                                                                                                                  container.getContainerOid()),
                                                                                                          container.getContainerOtype());
        baseLineDTO.setClassId(String.valueOf(typeBasedRuleEditDTO.getClassificationOid()));


        baseLineDTO.setName(partDetailsVO.getIdentifierDisplayName());

        baseLineDTO.setTopObjectOType(partDetailsVO.getContainerotype());
        baseLineDTO.setTopObjectOid(partDetailsVO.getContaineroid());
        if (typeTrees != null && typeTrees.size() > 0) {
            baseLineDTO.setTypeOid(typeTrees.get(0).getOid());
            baseLineDTO.setTypeOtype(typeTrees.get(0).getOtype());
        }


        baseLineDTOList.add(baseLineDTO);
        List<BigInteger> oidList = typlmBaseLineService.batchCreateBaseLine(baseLineDTOList);
        if (oidList != null && oidList.size() > 0) {
            TyplmBaseLineMemberAddDTO typlmBaseLineMemberAddDTO = new TyplmBaseLineMemberAddDTO();
            IdentifierEntity baseLineEntity = new IdentifierEntity();
            baseLineEntity.setOid(new BigInteger(String.valueOf(oidList.get(0))));
            baseLineEntity.setOtype("ty.inteplm.baseline.CTyBaseLine");

            List<IdentifierEntity> refObjList = new ArrayList<>();

            IdentifierEntity refEntity = new IdentifierEntity();
            refEntity.setOid(new BigInteger(String.valueOf(partDetailsVO.getOid())));
            refEntity.setOtype(partDetailsVO.getOtype());
            refObjList.add(refEntity);


            TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
            if (typlmPartBomService != null) {
                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(partDetailsVO.getView());
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("N");
                expandBomTreeByFilterDTO.setFatherNumber(partDetailsVO.getObjectNumber());
                expandBomTreeByFilterDTO.setFatherOid(String.valueOf(partDetailsVO.getOid()));
                expandBomTreeByFilterDTO.setFatherOtype(partDetailsVO.getOtype());
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(false);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);

                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);

                for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                    PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                    if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                        IdentifierEntity nrefEntity = new IdentifierEntity();
                        nrefEntity.setOid(new BigInteger(String.valueOf(partBomTree.getPartoid())));
                        nrefEntity.setOtype(partBomTree.getPartotype());
                        refObjList.add(nrefEntity);
                    }
                }
            }

            typlmBaseLineMemberAddDTO.setBaseLineInfo(baseLineEntity);
            typlmBaseLineMemberAddDTO.setRefObjList(refObjList);

            TyplmBaseLineMemberCheckResultVO typlmBaseLineMemberCheckResultVO = typlmBaseLineMemberService.checkObjectAddBaseLine(
                    typlmBaseLineMemberAddDTO);
            boolean flag = typlmBaseLineMemberService.addBaseLineMember(typlmBaseLineMemberCheckResultVO);
            if (flag == true) {
                return 1;
            }
        }

        return -1;
    }

}
